package com.snail.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.snail.model.pojo.mall.BizOrder;



import com.snail.service.serviceImp.BizOrderServiceImpl;
import com.snail.utils.PayUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/alipay")
public class AlipayController {

    @Autowired
    private PayUtil payUtil;
    @Autowired
private BizOrderServiceImpl bizOrderService;
    /**
     * 创建支付订单
     * @param orderNo 订单编号
     * @param amount 金额
     * @param subject 商品标题
     * @return 支付页面HTML
     */
    @GetMapping("/create")
    public String createOrder(@RequestParam String orderNo,
                              @RequestParam String amount,
                              @RequestParam String subject) {
        try {
            System.out.println(orderNo);
            System.out.println(amount);
            System.out.println(subject);
            System.out.println("sadasd");
            return payUtil.createOrder(orderNo, amount, subject);
        } catch (Exception e) {
            e.printStackTrace();
            return "支付创建失败: " + e.getMessage();
        }
    }
    @PostMapping("/refund")
    public Map<String, Object> refund(@RequestParam String orderNo,@RequestParam String refundAmount,@RequestParam String refundReason) {
        Map<String, Object> result = new HashMap<>();

        try {
//            String orderNo = refundRequest.get("orderNo");
//            String refundAmount = refundRequest.get("refundAmount");
//            String refundReason = refundRequest.get("refundReason");

            if (orderNo == null || refundAmount == null) {
                result.put("success", false);
                result.put("message", "订单号和退款金额不能为空");
                return result;
            }

            // 调用退款
            String refundResult = payUtil.refund(orderNo, refundAmount, refundReason);

            // 解析退款结果
            JSONObject refundJson = JSON.parseObject(refundResult);
            JSONObject alipayResponse = refundJson.getJSONObject("alipay_trade_refund_response");

            if (alipayResponse != null && "10000".equals(alipayResponse.getString("code"))) {
                // 退款成功，更新订单状态为已退款（状态码2）
                updateOrderStatus(orderNo, 2);

                result.put("success", true);
                result.put("message", "退款成功");
                result.put("data", alipayResponse);
            } else {
                result.put("success", false);
                result.put("message", "退款失败: " + (alipayResponse != null ?
                        alipayResponse.getString("sub_msg") : "未知错误"));
            }

        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "退款处理异常: " + e.getMessage());
        }

        return result;
    }
    /**
     * 支付宝同步通知
     */
    @GetMapping("/return")
    public String alipayReturn(HttpServletRequest request) {
        // 处理同步通知逻辑
        return "支付成功，正在跳转哈哈哈...";
    }

    /**
     * 支付宝异步通知
     */
    @PostMapping("/notify")
    public String alipayNotify(HttpServletRequest request) {
        // 1. 将请求参数转为Map
        Map<String, String> params = new HashMap<>();
        request.getParameterMap().forEach((key, values) -> {
            params.put(key, String.join(",", values));
        });

        // 2. 打印所有参数（调试用）
        System.out.println("============= 支付宝异步通知参数 =============");
        params.forEach((k, v) -> System.out.println(k + ": " + v));

        try {
            // 3. 验签（确保通知来自支付宝）
            boolean signVerified = payUtil.verifyNotification(params);
            if (!signVerified) {
                System.out.println("验签失败！可能是非法通知");
                return "failure";
            }

            // 4. 提取订单号并处理业务
            String tradeStatus = params.get("trade_status");
            String orderNo = params.get("out_trade_no");

            if ("TRADE_SUCCESS".equals(tradeStatus)) {
                System.out.println("支付成功！订单号: " + orderNo);

                // 5. 更新订单状态为1（已支付）
                updateOrderStatus(orderNo, 1); // 调用更新方法

                return "success";
            } else {
                System.out.println("交易未完成，状态: " + tradeStatus);
                return "failure";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "failure";
        }
    }


    private void updateOrderStatus(String orderNo, int status) {
        QueryWrapper<BizOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no", orderNo);

        BizOrder order = new BizOrder();
        order.setOrderStatus(status);
        order.setUpdateTime(new Date()); // 更新修改时间

        boolean updated = bizOrderService.update(order, wrapper);
        if (updated) {
            System.out.println("订单状态更新成功，订单号: " + orderNo);
        } else {
            System.out.println("⚠️ 订单状态更新失败，订单号: " + orderNo);
        }
    }

    // 转换request参数为Map
    private Map<String, String> convertRequestParams(HttpServletRequest request) {
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        requestParams.forEach((key, values) -> {
            String valueStr = String.join(",", values);
            params.put(key, valueStr);
        });
        return params;
    }

    /**
     * 查询订单状态
     * @param orderNo 订单编号
     * @return 订单状态
     */
    @GetMapping("/query")
    public String queryOrder(@RequestParam String orderNo) {
        try {
            return payUtil.queryOrder(orderNo);
        } catch (Exception e) {
            e.printStackTrace();
            return "查询失败: " + e.getMessage();
        }
    }
}
